# -*- coding: utf-8 -*-
import pandas as pd
from docx import Document
from docx.shared import Inches, Cm
from PIL import Image, ImageDraw, ImageFont
# from docx.enum.section import WD_ORIENTATION


g_tech = "点检表"


def read_sheet(ret, file_path, i):
    df = pd.read_excel(file_path, sheet_name=i)

    for index, row in df.iterrows():
        cmd = {}
        sn = ""
        st = ""

        for name in df.columns:
            if name.find("状态") != -1:
                st = "%s" % row[name]
                st = st.strip()

            if name.find("设备编号") != -1:
                sn = "%s" % row[name]
                sn = sn.strip()

            if name.find("点检项") != -1:
                t = "%s" % row[name]
                t = t.strip()
                if t and t != "nan":
                    cmd["name"] = t

            if name.find("图片") != -1:
                t = "%s" % row[name]
                t = t.strip()
                if t and t != "nan":
                    cmd["pic"] = t

        if not sn:
            continue

        if st == "N":
            continue

        if not cmd:
            continue

        if sn in ret:
            ret[sn].append(cmd)
        else:
            ret[sn] = [cmd]


if __name__ == '__main__':
    file_path = "./%s.xlsx" % g_tech

    doc = pd.ExcelFile(file_path)

    ret = {}

    for i in doc.sheet_names:
        read_sheet(ret, file_path, i)

    for sn, d in ret.items():
        dc = Document()

        section = dc.sections[0]
        section.page_height = Inches(11.7)
        section.page_width = Inches(8.3)

        section.top_margin = Cm(0.5)
        section.bottom_margin = Cm(0.5)
        section.left_margin = Cm(0.5)
        section.right_margin = Cm(0.5)
        # section.orientation = WD_ORIENTATION.LANDSCAPE

        dc.add_heading("%s  点检" % sn, 0)

        for v in d:
            if "name" not in v:
                continue

            name = u"%s" % v["name"]

            if "pic" not in v:
                continue

            pic = "%s" % v["pic"]
            if pic == "nan":
                continue

            path = "./pic/%s.png" % pic
            tmp_path = "./pic/tmp.png"
            font = ImageFont.truetype("font.ttc", size=42)
            f_x = 10
            f_y = 10

            color = (196, 244, 211)

            bg = Image.open(path)
            draw = ImageDraw.Draw(bg)

            bg_w, bg_h = bg.size

            draw.rectangle((0, 0, bg_w, 62), fill=color)
            draw.text((f_x, f_y), name, fill="black", font=font)

            bg.save(tmp_path)

            dc.add_picture(tmp_path, width=Cm(20))

        dc.save("./ck/%s.docx" % sn)

        print("Done: %s" % sn)
